package es.udc.pfc.davidparedes.web.pages.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;

import es.udc.pfc.davidparedes.model.storeservice.StoreService;
import es.udc.pfc.davidparedes.model.task.Task;
import es.udc.pfc.davidparedes.model.taskservice.TaskService;
import es.udc.pfc.davidparedes.model.universe.Universe;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.GlobalNames;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;
import es.udc.pfc.davidparedes.model.vendor.Vendor;

import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.MANAGER_OR_ABOVE)
public class UpdateTask {
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private UserService userService;
    
    @Inject
    private TaskService taskService;
    
    @Inject
    private StoreService storeService;

    @Property
    private Date startDate;
    
    @Property
    private Date endDate;
    
    @Property
    private String startTime;
    
    @Property
    private String endTime;
    
    @Property
    private Vendor vendor;
    
    @Property
    private List<Vendor> universeVendors;
    
    @Property
    private String taskType;
    
    @Property
    private List<String> taskTypes;
    
    @Property
    private Long updateTaskId;
    
    @Property
    private Long removeTaskId;
    
    @Component
    private Form updateTaskForm;
    
    @Component
    private Form removeTaskForm;
    
    @Inject 
    private PageRenderLinkSource pageLinkSource; 
    
    
    void onActivate(Long id) {
    	try {
    		
    		Task task = taskService.findTask(id);
    		updateTaskId = removeTaskId = id;
    		
    		Universe universe = task.getUniverse();
    		
    		universeVendors = new ArrayList<Vendor>();
    		universeVendors.addAll(universe.getVendors());
    		
    		taskType = Character.toString(task.getType());
    		
    		vendor = task.getVendor();
    		
    		taskTypes = new ArrayList<String>();
    		taskTypes.add(Character.toString(GlobalNames.TASK_NORMAL));
    		taskTypes.add(Character.toString(GlobalNames.TASK_VACATION));
    		taskTypes.add(Character.toString(GlobalNames.TASK_NIGHT));
    		taskTypes.add(Character.toString(GlobalNames.TASK_LOW));
    		taskTypes.add(Character.toString(GlobalNames.TASK_FESTIVE));
    		taskTypes.add(Character.toString(GlobalNames.TASK_ABSENTEEISM));
    		taskTypes.add(Character.toString(GlobalNames.TASK_COMPLEMENTARY_NORMAL));
    		taskTypes.add(Character.toString(GlobalNames.TASK_COMPLEMENTARY_FESTIVE));
    		taskTypes.add(Character.toString(GlobalNames.TASK_COMPLEMENTARY_NIGHT));
    		
    		startDate = task.getStart().getTime();
        	Integer startHour = task.getStart().get(Calendar.HOUR_OF_DAY);
        	Integer startMin = task.getStart().get(Calendar.MINUTE);
        	startTime = formatTime(startHour.toString()) + ":" + formatTime(startMin.toString());
        	
        	endDate = task.getEnd().getTime();
        	Integer endHour = task.getEnd().get(Calendar.HOUR_OF_DAY);
        	Integer endMin = task.getEnd().get(Calendar.MINUTE);
        	endTime = formatTime(endHour.toString()) + ":" + formatTime(endMin.toString());
        	
			} catch (InstanceNotFoundException e) {
		}
    }

    Object onSuccessFromUpdateTaskForm() throws NumberFormatException, InstanceNotFoundException {
        
        String[] taskStartTime = startTime.split(":");
        Integer taskStartHour = Integer.parseInt(taskStartTime[0]);
        Integer taskStartMin = Integer.parseInt(taskStartTime[1]);
        Calendar taskStart = Calendar.getInstance();
        taskStart.setTime(startDate);
        if ((0 <= taskStartHour) && (taskStartHour <= 23) && (0 <= taskStartMin) && (taskStartMin <= 59)) {
	        taskStart.set(Calendar.HOUR_OF_DAY, taskStartHour);
	        taskStart.set(Calendar.MINUTE, taskStartMin);
        } else {
        	return this;
        }
        
        String[] taskEndTime = endTime.split(":");
        Integer taskEndHour = Integer.parseInt(taskEndTime[0]);
        Integer taskEndMin = Integer.parseInt(taskEndTime[1]);
        Calendar taskEnd = Calendar.getInstance();
        taskEnd.setTime(endDate);
        if ((0 <= taskEndHour) && (taskEndHour <= 23) && (0 <= taskEndMin) && (taskEndMin <= 59)) {
	        taskEnd.set(Calendar.HOUR_OF_DAY, taskEndHour);
	        taskEnd.set(Calendar.MINUTE, taskEndMin);
        } else {
        	return this;
        }
        
        Task task = taskService.findTask(updateTaskId);
        
        if (taskStart.before(taskEnd)) {
        	try {
        		taskService.updateTask(task.getTaskId(), taskStart, taskEnd, (char)taskType.charAt(0), vendor.getUserProfileId(), task.getUniverse().getUniverseId());
			} catch (InstanceNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        return pageLinkSource.createPageRenderLinkWithContext("user/UniverseSchedule", task.getUniverse().getUniverseId());
        
    }
    
    Object onSuccessFromRemoveTaskForm() throws InstanceNotFoundException {
    	Task task = taskService.findTask(removeTaskId);
    	taskService.removeTask(task.getTaskId());
    	return pageLinkSource.createPageRenderLinkWithContext("user/UniverseSchedule", task.getUniverse().getUniverseId());
    }
        
    public ValueEncoder<Vendor> getVendorEncoder() {

        return new ValueEncoder<Vendor>() {

            @Override
            public String toClient(Vendor value) {
                return String.valueOf(value.getUserProfileId()); 
            }

            @Override
            public Vendor toValue(String id) { 
            	
            	Vendor vendor = new Vendor();
                try {
					vendor = userService.findVendor(Long.parseLong(id));
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstanceNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                
                return vendor;
            }
        };
            
    }
    
    private String formatTime(String s) {
    	if (s.length()<2) {
    		s="0"+s;
    	}
    	return s;
    }

}
